package com.qskj.springsecurity.single.config;

import com.qskj.springsecurity.single.filter.VerificationCodeFilter;
import com.qskj.springsecurity.single.handler.FailtureHandler;
import com.qskj.springsecurity.single.handler.SuccessHandler;
import com.qskj.springsecurity.single.provider.ImageAuthenticationProvider;
import com.qskj.springsecurity.single.security.MyWebAuthenticationDetailsSource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;

/**
 * @Auther shikf
 * @Date 2021-02-05 11:46
 */
@Configuration
@EnableWebSecurity
@Slf4j
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource dataSource;
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        jdbcTokenRepository.setDataSource(dataSource);
        http.authorizeRequests()
                .antMatchers("/admin/api/**").hasRole("ADMIN")
                .antMatchers("/user/api/**").hasRole("USER")
                .antMatchers("/app/api/**").hasAuthority("TEST")
                .anyRequest().authenticated()
                .and()
                .formLogin()
                // 使登录页不设限访问
                .permitAll()
                .and()
                .logout()
                // 指定接收注销登录的路由
                .logoutUrl("/myLogout")
                // 注销成功重定向到该路径下
                .logoutSuccessUrl("/")
                // 注销成功的处理方式，不同于logoutSuccessUrl方式，logoutSuccessHandler更加灵活
                .logoutSuccessHandler(new LogoutSuccessHandler() {
                    @Override
                    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
                        log.info("------------------LogoutSuccessHandler--------------------");
                    }
                })
                // 使该用户的httpSession失效
                .invalidateHttpSession(true)
                // 注销成功删除指定的cookie
                .deleteCookies("cookie1","cookie2")
                // 用于注销的处理句柄，允许自定义一些清理策略，事实上logoutSuccessHandler也能做到
                .addLogoutHandler(new LogoutHandler() {
                    @Override
                    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
                        log.info("------------------LogoutHandler--------------------");
                    }
                })
                .and()
                .rememberMe()
                .key("qskj")
                .userDetailsService(userDetailsService)
                .tokenRepository(jdbcTokenRepository)
                .and()
                .csrf().disable()
                .sessionManagement().maximumSessions(1)
        ;
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring()
                .antMatchers("/css/**")
                .antMatchers("/js/**")
                .antMatchers("/kaptcha");
    }

    @Bean
    public PasswordEncoder noOpPasswordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }
}
